package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Objects;

import static org.apache.commons.lang3.ObjectUtils.min;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
//        Employee = employeeMapper.getByUsername(username);

        // 构造查询条件
        QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<Employee>()
                .eq("username", username);
        Employee employee = employeeMapper.selectOne(employeeQueryWrapper);
//        Employee employee = getOne(employeeQueryWrapper);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工业务方法
     *
     * @param employeeDTO
     */
    @Override
//    @AutoFill(value = OperationType.INSERT)
    public void create(EmployeeDTO employeeDTO) {

//        System.out.println("current thread id" + Thread.currentThread().getId());

        Employee employee = new Employee();

        // 拷贝属性
        BeanUtils.copyProperties(employeeDTO, employee);

        // 设置其余属性
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        // 设置时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // 设置创建、修改者 id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        // 持久层接口，修改数据库
        employeeMapper.insert(employee);

    }

    /**
     * 分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {

        String name = employeePageQueryDTO.getName();

        // 构建分页条件
        Page<Employee> page = Page.of(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        // 构建查询条件
        lambdaQuery()
                .like(name != null, Employee::getName, name)
                .page(page);

        PageResult pageResult = new PageResult();

        // 设置属性
        // TODO 分页查询失败，需要修改
        pageResult.setTotal(page.getRecords().size());

        // 手动分页

        // 左端 = （页数 - 1）* 每页条数
        int l = (employeePageQueryDTO.getPage() - 1) * employeePageQueryDTO.getPageSize();

        // 左端起点超出起点
        if (l >= page.getRecords().size()) {
            return pageResult;
        }

        // 右端 = 左端 +
        int r = l + employeePageQueryDTO.getPageSize();
        r = min(r, page.getRecords().size());
        pageResult.setRecords(page.getRecords().subList(l, r));

        return pageResult;
    }

    /**
     * 设置员工状态
     *
     * @param status
     * @param id
     * @return
     */
    @Override
//    @AutoFill(value = OperationType.UPDATE)
    public Employee transitionStatus(Integer status, Long id) {
        // 查询员工 id
        Employee employee = employeeMapper.selectById(id);

        if (employee == null) {
            return null;
        }

        // 设置状态
        employee.setStatus(status);

        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        // 构造更新条件
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<Employee>()
                .eq(Employee::getId, employee.getId());
        employeeMapper.update(employee, lambdaQueryWrapper);
//        employeeMapper.updateById(employee);

        return employee;
    }

    /**
     * 根据id 查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Employee queryById(Long id) {
        // 调用持久层查询
        return employeeMapper.selectById(id);
    }

    @Override
//    @AutoFill(value = OperationType.UPDATE)
    public Employee updateById(EmployeeDTO employeeDTO) {
        Long id = employeeDTO.getId();

        // 查询待修改的员工
        Employee employee = employeeMapper.selectById(id);

        // 拷贝属性
        BeanUtils.copyProperties(employeeDTO, employee);
        // 设置修改任何修改时间
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());

        // 构造修改条件
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<Employee>()
                .eq(Employee::getId, id);
        // 修改员工信息
        employeeMapper.update(employee, employeeLambdaQueryWrapper);

        return employee;
    }

    @Override
    public Employee updatePassword(PasswordEditDTO passwordEditDTO) {
        // 取出 Id
        Long id = passwordEditDTO.getEmpId();


        // 取出密码
        String oldPassword = passwordEditDTO.getOldPassword();
        String newPassword = passwordEditDTO.getNewPassword();

        // 根据 id 查询员工
        Employee employee = employeeMapper.selectById(id);

        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);

        }

        // 将原密码 md5 转换
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());

        // 校验原密码是否相同
        if (!oldPassword.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }

        // 将新密码进行 md5 加密
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());

        // 设置新密码
        employee.setPassword(newPassword);
        // 调用持久层接口修改数据库
        employeeMapper.updateById(employee);

        return null;
    }


}
